package com.outsourcing.bottle.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity;
import com.aviary.android.feather.library.utils.StringUtils;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.Utility;
import com.outsourcing.bottle.widget.crop.CropImage;
import com.outsourcing.bottle.widget.crop.CropImageView;
/**
 * 
 * @author 06peng
 *
 */
public class CropImageActivity extends BasicActivity {

	private static final String TAG = CropImageActivity.class.getSimpleName();
	private static final int RESULT_CROPIMAGE_WITH_DATA = 101;
	private CropImageView mImageView;
	private Bitmap mBitmap;

	private CropImage mCrop;
	
	/** session id for the hi-res post processing */
	private String mSessionId;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.crop_view);
		init();
	}
	String path = null;
	private void init() {
		path = getIntent().getStringExtra("path");
		Log.d("may", "path=" + path);
		
//		mBitmap = BitmapFactory.decodeFile(path);
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPurgeable = true;
		options.inInputShareable = true;
		options.inSampleSize = 5;
		try {
			if (android.os.Build.VERSION.SDK_INT < 11) {
				BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		FileInputStream fin = null;
		try {
			fin = new FileInputStream(path);
			mBitmap = BitmapFactory.decodeStream(fin, null, options);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally{
			if (null != fin) {
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		
		mImageView = (CropImageView) findViewById(R.id.image);
		mImageView.setImageBitmap(mBitmap);
		mImageView.setImageBitmapResetBase(mBitmap, true);

		mCrop = new CropImage(this, mImageView, true, 600, 600);
		mCrop.crop(mBitmap);
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			File uploadFileDir = new File(
					Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
			File file = new File(uploadFileDir, "upload.jpeg");
			if (file.exists()) {
				file.delete();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.cancel:
			mCrop.cropCancel();
			break;
//		case R.id.crop:
//			mCrop.crop(mBitmap);
//			break;
		case R.id.save:
//			inputDialog();
			String cacheDir = android.os.Environment.getExternalStorageDirectory()+ "/" + AppContext.SD_PATH + "/upload";
			saveBitmap(cacheDir,mCrop.cropAndSave(mBitmap));
			File file = new File(cacheDir,"upload.jpeg");
			
			if (null != file) {
				Uri fileUri = Uri.fromFile(file);
				startFeather(fileUri);
			}
//			finish();
			break;
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == RESULT_CROPIMAGE_WITH_DATA) {
			if (resultCode == RESULT_OK) {
				finish();
			}else {
				File uploadFileDir = new File(
						Environment.getExternalStorageDirectory() + "/" + AppContext.SD_PATH, "upload");
				File file = new File(uploadFileDir, "upload.jpeg");
				if (file.exists()) {
					file.delete();
				}
				finish();
			}
		}
	};
	
	String mOutputFilePath;

	/**
	 * Once you've chosen an image you can start the feather activity
	 * 
	 * @param uri
	 */
	private void startFeather( Uri uri ) {

		if ( !Utility.isExternalStorageAvilable() ) {
			return;
		}

		// create a temporary file where to store the resulting image
		File file = Utility.getNextFileName();
		if ( null != file ) {
			mOutputFilePath = file.getAbsolutePath();
		} else {
			new AlertDialog.Builder( this ).setTitle( android.R.string.dialog_alert_title ).setMessage( "Failed to create a new File" )
					.show();
			return;
		}

		Intent newIntent = new Intent( this, FeatherActivity.class );

		newIntent.putExtra( "From_Type", Constants.ACTIVITY_EDIT );
		
		// set the source image uri
		newIntent.setData( uri );

		// pass the required api_key and secret ( see
		// http://developers.aviary.com/ )
		newIntent.putExtra( "API_KEY", Utility.API_KEY );

		newIntent.putExtra( "output", Uri.parse( "file://" + mOutputFilePath ) );
		newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.PNG.name() );
		newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 );
		newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true );

		final DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics( metrics );
		int max_size = Math.min( metrics.widthPixels, metrics.heightPixels );

		// you can pass the maximum allowed image size, otherwise feather will determine
		// the max size based on the device memory
		// Here we're passing the current display size as max image size because after
		// the execution of Aviary we're saving the HI-RES image so we don't need a big
		// image for the preview
		max_size = (int) ( (double) max_size / 0.8 );
		newIntent.putExtra( "max-image-size", max_size );

		// Enable/disable the default borders for the effects
		newIntent.putExtra( "effect-enable-borders", true );

		mSessionId = StringUtils.getSha256( System.currentTimeMillis() + Utility.API_KEY );
		Log.d( TAG, "session: " + mSessionId + ", size: " + mSessionId.length() );
		newIntent.putExtra( "output-hires-session-id", mSessionId );

		startActivityForResult(newIntent, RESULT_CROPIMAGE_WITH_DATA);
	}
	
	public void saveBitmap(String dir,Bitmap bmp) {
		File file = new File(dir);
		String path = null;
		if (!file.exists())
			file.mkdirs();
		try {
			path = file.getPath() + "/upload.jpeg";
			FileOutputStream fileOutputStream = new FileOutputStream(path);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
			fileOutputStream.flush();
			fileOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
